package com.qbw.app.module.common.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.http.okhttp.HttpTask;
import com.qbw.app.R;
import com.qbw.app.databinding.CommonActivitySelectCountryAreaBinding;
import com.qbw.app.model.Country;
import com.qbw.app.module.common.adapter.CountryAreaAdapter;
import com.qbw.app.module.common.holder.CountryAreaItemHolder;
import com.qbw.app.module.common.util.HttpRequestUtil;
import com.qbw.app.module.common.util.UniversalToastUtil;

import static com.qbw.app.Constant.KEY_SELECTED_COUNTRY;
import static com.qbw.app.request.impl.CommonRequest.METHOD_COUNTRY_LIST;

/**
 * @author QBW
 * @date 2019/9/16
 */
public class SelectCountryAreaActivity extends CommonActivity<CommonActivitySelectCountryAreaBinding> implements CountryAreaItemHolder.Listener {

    private CountryAreaAdapter mAdapter;

    public static void startForResult(Activity context, int requestCode) {
        Intent intent = new Intent(context, SelectCountryAreaActivity.class);
        context.startActivityForResult(intent, requestCode);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.common_activity_select_country_area;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding.title.setListener(this);
        mBinding.rcv.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rcv.setAdapter(mAdapter = new CountryAreaAdapter(this));
        mGeneralManager.getRequestManager().getCommonRequest().getCountryList(this).execute();
    }

    @Override
    public void onHttpStart(HttpTask httpTask) {
        super.onHttpStart(httpTask);
        String method = httpTask.getMethod();
        if (method.equals(METHOD_COUNTRY_LIST)) {
            showLoadingDialog("");
        }
    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (method.equals(METHOD_COUNTRY_LIST)) {
            Country.Response response = (Country.Response) entity;
            mAdapter.addChild(response.getData());
            closeLoadingDialog();
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        message = HttpRequestUtil.getMessage(errorCode, message);
        String method = httpTask.getMethod();
        if (method.equals(METHOD_COUNTRY_LIST)) {
            UniversalToastUtil.showFailedIconToast(message);
            closeLoadingDialog();
        }
    }

    @Override
    public void onSelectCountryArea(Country country) {
        Intent intent = new Intent();
        intent.putExtra(KEY_SELECTED_COUNTRY, country);
        setResult(RESULT_OK, intent);
        finish();
    }
}
